/**
 * 一个典型的，包含上拉刷新和下拉加载的页面
 * 配置
 * url 数据接口
 * params 额外参数
 * enableReachBottom 是否开启下拉加载，默认是
 * enablePullDown 是否开启上拉刷新，默认是（需要在页面中配置)
 */
module.exports = config => {
    config = Object.assign({
        params: {},
        enableReachBottom: true,
        enablePullDown: true,
        methods: {},
        auto: true
    }, config)
    if (!config.url) {
        throw new Error("需要配置url参数!")
    }
    Page(Object.assign({
        onLoad: function(options) {
            this.setData(options)
            typeof config.onLoad === "function" && config.onLoad.call(this)
            console.log(config)
            config.auto === true && this.loadData()
        },
        loadData(params = {}) {
            let {
                page = 1, total = 2, loading = false, list = []
            } = this.data
            if (page > total || loading) {
                return
            }
            this.setData({
                loading: true
            })
            const data = Object.assign(config.params, params)
            data.page = page
            getApp().http.get(config.url, {
                data,
            }).then(res => {
                page++
                total = res.data.total
                if (config.dataFilter && typeof config.dataFilter === "function") {
                    res.data.items = config.dataFilter(res.data.items)
                }
                list.push(...res.data.items)
                loading = false
                this.setData({
                    loading,
                    page,
                    total,
                    list
                })
                typeof config.onDataLoad === 'function' && config.onDataLoad.call(this, res.data)
                wx.stopPullDownRefresh()
                wx.hideLoading()
            })
        },
        onReachBottom() {
            this.loadData()
        },
        onPullDownRefresh() {
            this.reload()
        },
        reload() {
            this.setData({
                page: 1,
                total: 2,
                list: [],
            })
            this.loadData()
        }
    }, config.methods))
}